<template>
  <div class="app-container">
    <u-page-config
      :filter-array="filterArray"
      v-model="filter"
      :actionBtn="actionBtn"
      label-width="100px"
      :getList="getList"
      :tableData="tableData"
      :tableColumn="tableColumn"
      :total="total"
      :loading="loading"
      showSelection
      @handleSelectionChange="handleSelectionChange"
      @addRow="addRow"
      @removeRow="removeRow"
      @editRow="editRow"
      @rowDetail="rowDetail"
      @export="handleExport"
    >
      <template #branchCode="scope">
        <treeselect
          style="width:240px"
          v-model="filter.data.branchCode"
          :options="branchDataOptions"
          :normalizer="branchNormalizer"
          :show-count="true"
          placeholder="选择网点"
          noOptionsText="暂无选项"
          noResultsText="没有匹配的搜索结果"
        />
      </template>

      <template #typeOptions="{ row, item }">
        {{ getDictLabel(typeOptions, row.type) }}
      </template>

      <template #systemOptions="{ row, item }">
        {{ getDictLabel(systemOptions, row.systemType) }}
      </template>
    </u-page-config>
    <!-- 修改政策 -->
    <el-dialog :title="title" :visible.sync="visible" width="1200px" :close-on-click-modal="false">
        <u-form
          ref="uFormRef"
          label-width='134px'
          v-model="form"
          :defaultForm="defaultForm"
          :formArray="formArray"
          :detail-array="formArray"
          :show-btn="false"
          @submit="onsubmit"
          @close="visible = false"
          :mode="mode"
        >
          <template #branchCode="scope">
            <treeselect style="width:100%" v-model="form.branchCode" :options="branchDataOptions"
                        :normalizer="branchNormalizer" :show-count="true" placeholder="选择网点" noOptionsText="暂无选项"
                        noResultsText="没有匹配的搜索结果"/>
          </template>

          <template #systemType="scope">
            <el-checkbox-group v-model="form.systemType">
              <template v-for="checkbox in systemOptions">
                <el-checkbox :label="checkbox.value">{{ checkbox.label }}</el-checkbox>
              </template>
            </el-checkbox-group>
          </template>

          <template #image="scope">
            <u-file-upload :value="form.pic" :limit="3" :fileSize="10" @input="imageUploadChange"/>
          </template>
        </u-form>
    </el-dialog>
  </div>
</template>

<script>
import UPageConfig from '@/components/uPageConfig/index'
import UForm from '@/components/uForm'
import table from "@/mixin/uTable";
import Treeselect from "@riophae/vue-treeselect";
import {
  listTInfoZxzc,
  getTInfoZxzc,
  delTInfoZxzc,
  addTInfoZxzc,
  updateTInfoZxzc
} from "@/api/info/TInfoZxzc";
import {listManager} from "@/api/device/placeManager";
import {updateNotice} from "@/api/system/notice";

export default {
  name: "UpdatePlan",
  mixins: [table],
  //3
  components: {UPageConfig, UForm, Treeselect},
  data() {
    return {
      form: {
        systemType: []
      },
      typeOptions: [
        {label: '政策', value: 1},
        {label: '通知', value: 2},
        {label: '公告', value: 3},
      ],
      systemOptions: [
        {label: '门户', value: '1'},
        {label: '填表系统', value: '2'},
        {label: '表单电子范例系统', value: '3'},
        {label: '智能查询系统', value: '4'},
      ],
      publishStatusOptions: [
        {label: '发布', value: 0},
        {label: '不发布', value: 1}
      ],
      filterArray: [
        {label: "网点", key: "branchCode", type: "slot", slot: 'branchCode' },
        {label: "信息类型", key: "type", type: "select"},
        {label: "系统类型", key: "systemType", type: "select"},
        {label: "标题", key: "title", type: "input"}
      ],
      tableColumn: [
        {label: "信息类型", prop: "type", type: 'slot', slot: 'typeOptions'},
        {label: "网点", prop: "branchName"},
        {label: "系统类型", prop: "systemType", type: 'slot', slot: 'systemOptions'},
        {label: "标题", prop: "title", showOverflowTooltip: true},
        {label: "简要描述", prop: "description", showOverflowTooltip: true},
        // {label: "详细信息", prop: "detail", type: 'slot', slot: 'detail'},
        {
          label: "操作", type: "btn", attr: {width: 180}, btnArr: [
            // { icon: "el-icon-view", text: "详细", emit: "rowDetail" },
            {
              icon: "el-icon-edit-outline",
              text: "修改",
              emit: "editRow",
              permissions: 'info:TInfoZxzc:edit'
            },
            {
              icon: "el-icon-delete",
              text: "删除",
              emit: "removeRow",
              permissions: 'info:TInfoZxzc:remove'
            },
          ]
        }
      ],
      actionBtn: [
        {
          type: 'primary',
          text: '新增',
          icon: 'el-icon-plus',
          emit: 'addRow',
          permissions: 'info:TInfoZxzc:add'
        },
        {
          type: 'success',
          text: '修改',
          icon: 'el-icon-edit',
          emit: 'editRow',
          permissions: 'info:TInfoZxzc:edit',
          disabledRule: () => this.ids.length !== 1
        },
        {
          type: 'danger',
          text: '删除',
          icon: 'el-icon-delete',
          emit: 'removeRow',
          permissions: 'info:TInfoZxzc:remove',
          disabledRule: () => this.ids.length === 0
        },
        {
          type: 'warning',
          text: '导出',
          icon: 'el-icon-download',
          emit: 'export',
          permissions: 'info:TInfoZxzc:export'
        },
      ],
      // 修改表单默认必填参数 重置表单时需要用到
      defaultForm: {
        title: '',
        type: '',
        description: '',
        detail: '',
        pic: '',
        branchCode: '',
        systemType: [],
        remark: '',
      },
      formArray: [
        {
          label: "信息标题：", key: "title", col: 24, type: "input",
          rule: {required: true, message: '标题不能为空！', trigger: 'blur'},
        },
        {
          label: "信息概述：", key: "description", col: 24, type: "input", placeholder: "请输入30字左右概述内容",
          rule: {required: true, message: '信息概述不能为空！', trigger: 'blur'},
        },
        {
          label: "信息类型: ", key: "type", col: 12, type: "select", options: [],
          rule: {required: true, message: '信息类型不能为空！', trigger: 'change'},
        },
        {
          label: "文号: ", key: "proof", col: 12, type: "input", placeholder: "XXX[2022]X号(非必填)"
        },
        {
          label: "投放网点: ", key: "branchCode", col: 12, type: "slot", slot: 'branchCode',
          rule: {required: true, message: '投放网点不能为空！', trigger: 'blur'},
        },
        {
          label: "备注: ", key: "remark", col: 12, type: "input", placeholder: "请输入备注",
        },
        {
          label: "发布时间：", key: "publishTime", col: 12, type: "datetime",
          attr: {defaultValue: Date.now()},
          rule: {required: true, message: '处理时间不能为空！', trigger: 'blur'},
        },
        {
          label: "发布状态：", key: "publishStatus", col: 12, type: "radio", options: [],
          rule: {required: true, message: '发布状态不能为空！', trigger: 'blur'},
        },
        {
          label: "投放设备：", key: "systemType", col: 24, type: "slot", slot: 'systemType',
          rule: {required: true, message: '投放设备不能为空！', trigger: 'blur'},
        },
        {
          label: "图标: ", key: "pic", col: 24, type: "slot", slot: 'image',
        },
        {
          label: "内容：", key: "detail", col: 24, type: "editor",
        },
      ],
    };
  },
  computed: {
    // 4
    // 网点树形数据
    branchDataOptions() {
      return this.$store.state.device.branchDataOptions || []
    },
  },
  methods: {
    // 5
    /** 转换分组树形图数据结构 */
    branchNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.branchCode,
        label: node.branchName,
        children: node.children || undefined,
      };
    },
    // 表单提交接口相关配置
    formSubmitFunConfig() {
      return {
        addFunc: addTInfoZxzc,
        modifyFunc: updateTInfoZxzc,
        pk: 'id',
        options: {
          ...this.form,
          systemType: this.form.systemType.join(',')
        },
        cbFunc: () => {
          this.visible = false
        }
      }
    },
    // 删除
    removeRow(row) {
      const id = row ? row.id : this.ids;
      this.removeTip(async () => {
        await delTInfoZxzc(id)
      }, row && row.id ? '该项数据' : '已勾选项数据')
    },
    // 添加
    addRow() {
      this.mode = 'form';
      this.title = "添加政策";
      this.visible = true;
    },
    // 修改
    async editRow(row) {
      this.mode = 'form'
      this.title = "修改政策";
      if (row) { //点击的表格内修改按钮
        this.form = JSON.parse(JSON.stringify({
          ...row,
          systemType: row.systemType ?.split(',') || ''
        }))
      } else { //点击表格上方修改按钮
        const selectedItem = this.tableData.find(item => this.ids[0] === item.id) || {}
        this.form = JSON.parse(JSON.stringify({
          ...selectedItem,
          systemType: selectedItem.systemType ?.split(',') || ''
        }))
      }
      this.visible = true
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },
    // 添加文件上传成功、删除图片时都会被调用()
    imageUploadChange(imgUrl) {
      this.form.pic = imgUrl
    },
    /** 查询政策列表 */
    getList() {
      this.getInit(listTInfoZxzc, {})
    },

    /** 详细按钮操作 */
    rowDetail(row) {
      this.mode = 'text'
      // 直接拿到这一行的数据赋值
      this.visible = true
      this.form = JSON.parse(JSON.stringify({
        ...row,
        systemType: row.systemType ?.split(',') || ''
      }))
      this.title = '详细信息'
      // 如果当前行数据不完整 调接口拿详情数据(防止点击之后政策消失)
      // this.getDetail('详细信息', getTInfoZxzc, row.id)
    },
    /** 返回设备部署页面 */
    goBack() {
      this.$router.go(-1);
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      const ids = this.ids;
      const params = this.getListRequestParams();
      this.download(
        "/info/TInfoZxzc/export",
        params,
        `政策列表_${currentDate}.xlsx`,
      );
    }
  },
  created() {
    try {
      // 绑定选择列表
      this.formArray.find(item => item.key === 'type').options = this.typeOptions;
      // 绑定选择列表
      this.formArray.find(item => item.key === 'systemType').options = this.systemOptions;
      this.formArray.find(item => item.key === 'publishStatus').options = this.publishStatusOptions;
      this.filterArray.find(item => item.key === 'type').options = this.typeOptions;
      this.filterArray.find(item => item.key === 'systemType').options = this.systemOptions;
    } catch (e) {
      console.log("找不到对应表单项", e)
    }
  }
}
</script>

<style lang="scss" scoped>
.form-item-wrap {
  display: flex;
}

</style>
